package com.example.vv.config;

import java.util.Arrays;
import java.util.Objects;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

public class ElasticsearchExample {
    public static void main(String[] args) throws Exception {
        String elasticNodes = "es1-auth-dev.yzw.cn,es2-auth-dev.yzw.cn,es3-auth-dev.yzw.cn";
        int elasticPort = 9200;
        int connectTimeout = 30000;
        int socketTimeout = 60000;
        int connectionRequestTimeout = 0;
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                AuthScope.ANY, new UsernamePasswordCredentials("elastic", "tdvUggwHLKLmmhijfwmO"));
        HttpHost[] httpHosts = Arrays.stream(elasticNodes.split(","))
                .map(host -> new HttpHost(host, elasticPort))
                .filter(Objects::nonNull)
                .toArray(HttpHost[]::new);
        RestClientBuilder builder = RestClient.builder(httpHosts).setHttpClientConfigCallback(httpClientBuilder -> {
            RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
                    .setConnectTimeout(connectTimeout)
                    .setSocketTimeout(socketTimeout)
                    .setConnectionRequestTimeout(connectionRequestTimeout);
            httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            return httpClientBuilder;
        });

        RestHighLevelClient restClient = new RestHighLevelClient(builder);

        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("curr_wangdehai");
        SearchResponse response = restClient.search(searchRequest, RequestOptions.DEFAULT);
        System.err.println(response);
    }
}
